import 'dart:async';
import 'dart:io';

import 'package:cloud_phone_manager/data/LogItem.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_styled_toast/flutter_styled_toast.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

import '../provider/AdbCurrentChangeProvider.dart';
import '../utils/CmdUtils.dart';
import 'LogDropdownView.dart';

/// 日志显示模板
class LogView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _LogView();
}

class _LogView extends State<LogView> {
  Color tColor = Colors.black;
  List<LogItem> _logList = [];
  ScrollController _scrollController = ScrollController();
  TextEditingController tagController = TextEditingController();
  TextEditingController processController = TextEditingController();
  FocusNode tagFocusNode = FocusNode();
  FocusNode processFocusNode = FocusNode();
  Process? logcatProcess;
  String tag = "";
  StreamSubscription<String>? successCallback;
  String logPackageName = "";
  String level = "V";
  DateTime? dateTime;
  bool _mounted = false;
  AdbCurrentChangeProvider? provider;
  bool _isInit = false;

  @override
  void initState() {
    super.initState();
    _mounted = true;
    if (!_isInit) {
      _isInit = true;
      startListenLogcat();
    }
  }

  @override
  void dispose() {
    _mounted = false;
    super.dispose();
  }

  void startListenLogcat() {
    if (Process != null) {
      logcatProcess?.kill();
    }
    if (successCallback != null) {
      successCallback?.cancel();
    }
    DateTime now = DateTime.now();
    DateFormat dateFormat = DateFormat('yyyy-MM-dd HH:mm:ss');
    DateFormat dateFormatTwo = DateFormat('yyyy-MM-dd HH:mm:ss.SSS');
    if (dateTime == null) {
      CmdUtils.dateForDevice((success, error, process, suListener) {
        //debugPrint(success);
        try {
          if (success.isNotEmpty) {
            dateTime = dateFormat.parse(success);
            // String cmd = "adb logcat -t \"${dateFormatTwo.format(dateTime!)}\"";
            String cmd = "*:${level}";
            if (tag.isNotEmpty) {
              cmd = " $cmd -s $tag";
            }
            //debugPrint(cmd);
            if (_mounted) {
              setState(() {
                _logList.clear();
              });
            }
            CmdUtils.logcat(cmd, (success, error, process, suListener) {
              logcatProcess = process;
              successCallback = suListener;
              if (_logList.length > 5000) {
                _logList.removeRange(0, _logList.length ~/ 2);
              }
              if (_mounted) {
                setState(() {
                  _logList.add(LogItem(success));
                  _scrollController
                      .jumpTo(_scrollController.position.maxScrollExtent);
                });
              }
            });
          }
        } catch (ignores) {}
      });
    } else {
      String cmd = "*:${level}";
      if (tag.isNotEmpty) {
        cmd = " $cmd -s $tag";
      }
      if (_mounted) {
        setState(() {
          _logList.clear();
        });
      }
      CmdUtils.logcat(cmd, (success, error, process, suListener) {
        logcatProcess = process;
        successCallback = suListener;
        // debugPrint("长度：${_logList.length}");
        if (_logList.length > 5000) {
          _logList.removeRange(0, _logList.length ~/ 2);
        }
        if (_mounted) {
          setState(() {
            _logList.add(LogItem(success));
            _scrollController
                .jumpTo(_scrollController.position.maxScrollExtent);
          });
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (provider == null) {
      provider = Provider.of<AdbCurrentChangeProvider>(context);
      debugPrint("注册监听");
      provider?.addListener(() {
        debugPrint("开始刷新界面");
        startListenLogcat();
      });
    }
    return SizedBox(
      height: MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      child: Column(
        children: [
          SizedBox(
            width: MediaQuery.of(context).size.width,
            height: 60,
            child: Container(
              padding: const EdgeInsets.all(5),
              child: Row(
                children: [
                  Expanded(
                    flex: 4,
                    child: Container(
                      margin: const EdgeInsets.fromLTRB(20, 0, 0, 0),
                      child: TextField(
                        keyboardType: TextInputType.text,
                        controller: processController,
                        focusNode: processFocusNode,
                        decoration: const InputDecoration(
                          labelText: '进程选择',
                          border: OutlineInputBorder(),
                        ),
                        onEditingComplete: () {
                          tag = processController.text.toString();
                          startListenLogcat();
                        },
                        onTapOutside: (event) {
                          if (processFocusNode.hasFocus &&
                              logPackageName != processController.value.text) {
                            logPackageName = processController.value.text;
                            startListenLogcat();
                            processFocusNode.unfocus();
                          } else if (processFocusNode.hasFocus) {
                            processFocusNode.unfocus();
                          }
                        },
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: Container(
                      margin: const EdgeInsets.fromLTRB(20, 0, 0, 0),
                      child: Row(
                        children: [
                          Row(
                            children: [
                              const Text("等级："),
                              LogDropdownView((value) =>
                                  {level = value, startListenLogcat()})
                            ],
                          ),
                          Container(
                            margin: const EdgeInsets.fromLTRB(20, 0, 0, 0),
                            child: TextButton(
                                onPressed: () {
                                  pickFile().then((value) => {
                                        CmdUtils.pullFileToComputer(
                                            "/data/misc/logd", value ?? "",
                                            (success, error, process,
                                                successListener) {
                                          //debugPrint(success);
                                          if (error.isNotEmpty ||
                                              success.contains("error:")) {
                                            showToast("拉取日志失败",
                                                context: context);
                                          } else {
                                            //debugPrint(success);
                                          }
                                        })
                                      });
                                },
                                child: Text("导出日志")),
                          )
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
              color: Colors.black,
              child: ListView.builder(
                itemCount: _logList.length,
                controller: _scrollController,
                itemBuilder: (context, index) {
                  return SizedBox(
                    width: MediaQuery.of(context).size.width,
                    child: Text(
                      _logList[index].content,
                      style: TextStyle(
                          fontSize: 12, color: _logList[index].getColor()),
                    ),
                  );
                },
              ),
            ),
          )
        ],
      ),
    );
  }

  Future<String?> pickFile() async {
    String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
    return selectedDirectory;
  }
}
